import request from "utils/request";

const _import = (component) => () => import(`src/${component}.vue`);

/**
 * 排序
 * @param {*} a
 * @param {*} b
 * @returns
 */
const up = function (a, b) {
  return a.meta.sort - b.meta.sort;
};

export function filterAsyncRoutes(routes) {
  const res = [];
  routes.forEach((route) => {
    const tmp = {
      ...route,
      path: route.url,
      name: route.module_name,
      // component: _import(route.url),
      component:
        route.children && route.children.length > 0
          ? _import("layout/layout")
          : _import("pages/default/default"),
      meta: {
        title: route.module_name,
        sort: route.sort || 2,
      },
    };
    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children); //递归，处理子路由权限
    }
    res.push(tmp);
  });
  return res;
}

const state = {
  accessRoutes: [],
  isGetAccessRoute: false,
};

const mutations = {
  updateMenu(state, accessRoutes) {
    state.accessRoutes = accessRoutes;
  },
  updateGetAccessRoute(state, isGetAccessRoute) {
    state.isGetAccessRoute = isGetAccessRoute;
  },
  clearAccessRoute() {
    state.isGetAccessRoute = false;
    state.accessRoutes = [];
  },
};
const actions = {
  getMenus({ commit }) {
    return new Promise((resolve, reject) => {
      request.get("/access/list").then((ret) => {
        if (ret.code == 200) {
          const accessRoutes = filterAsyncRoutes(ret.data);
          // const accessRoutes = filterAsyncRoutes( AsyncRoute );
          commit("updateMenu", accessRoutes);
          commit("updateGetAccessRoute", true);
          resolve(accessRoutes);
        } else {
          reject(ret.message);
        }
      });
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
